//
//  DeletableTableViewCell.m
//  DeletableTableCell
//
//  Created by nhn on 12/30/14.
//  Copyright (c) 2014 CNUIC. All rights reserved.
//

#import "DeletableTableViewCell.h"

@implementation DeletableTableViewCell

- (void)initValues {
    self.edgeInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.rowSpace = 0;
    self.cellPerRow = 4;
    self.cellSize = CGSizeMake(100, 100);
    self.cellSpace = 0;
    self.isDeleting = NO;
    
    self.selectionStyle = UITableViewCellSelectionStyleNone;
}

- (instancetype)init {
    if (self = [super init]) {
        [self initValues];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initValues];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self initValues];
    }
    return self;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self initValues];
    }
    return self;
}

- (CGFloat)recalcLayout {
    CGFloat cellWith = (self.bounds.size.width-self.edgeInset.left-self.edgeInset.right-(self.cellPerRow-1)*self.cellSpace)/self.cellPerRow;
    CGFloat cellHeight = cellWith;
    self.cellSize = CGSizeMake(cellWith, cellHeight);
    
    NSUInteger totalCell = self.delegate?[self.delegate numberOfItmesInDeletableCell:self]:0;
    NSUInteger rowNum = (totalCell + self.cellPerRow-1)/self.cellPerRow;
    CGFloat totalHeight = rowNum * cellHeight + (rowNum?(rowNum-1)*self.rowSpace : 0) + self.edgeInset.top + self.edgeInset.bottom;
    
    return totalHeight;
}

- (void)arrangeCells {
    NSUInteger totalCell = self.delegate?[self.delegate numberOfItmesInDeletableCell:self]:0;
    if (!totalCell) {
        return;
    }
    
    if (self.cellArray) {
        for (UIView* view in self.cellArray) {
            [view removeFromSuperview];
        }
    }
    
    self.cellArray = [NSMutableArray array];
    
    for (int i=0; i<totalCell; i++) {
        NSUInteger row = i/self.cellPerRow;
        NSUInteger col = i%self.cellPerRow;
        
        CGFloat x = self.edgeInset.left + col*(self.cellSize.width+self.cellSpace);
        CGFloat y = self.edgeInset.top + row*(self.cellSize.height+self.rowSpace);
        
        UIView* cell = [[UIView alloc] initWithFrame:CGRectMake(x, y, self.cellSize.width, self.cellSize.height)];
        cell.userInteractionEnabled = YES;
//		cell.backgroundColor = [UIColor yellowColor];
        [self addSubview:cell];
        [self.cellArray addObject:cell];
        
        UIImage* image = self.delegate?[self.delegate deletableCell:self imageForIndex:i] : nil;
        UIImageView* imageView = [[UIImageView alloc] initWithImage:image];
        CGFloat sizeRatio = 0.7;
        CGSize imageViewSize = CGSizeMake(self.cellSize.width*sizeRatio, self.cellSize.height*sizeRatio);
        imageView.frame = CGRectMake(0, 0, imageViewSize.width, imageViewSize.height);
        imageView.center = CGPointMake(CGRectGetMidX(cell.bounds), CGRectGetMidY(cell.bounds));
        imageView.userInteractionEnabled = YES;
        UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressed:)];
        [imageView addGestureRecognizer:longPressRecognizer];
		UITapGestureRecognizer* tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapPressed:)];
		[imageView addGestureRecognizer:tapRecognizer];
        [cell addSubview:imageView];
        
        UIImage* delImage = [UIImage imageNamed:@"btn_delete.png"];
        UIButton* delButton = [UIButton buttonWithType:UIButtonTypeCustom];
        delButton.tag = 0XDB;
        [delButton setImage:delImage forState:UIControlStateNormal];
        [delButton addTarget:self action:@selector(deletePressed:) forControlEvents:UIControlEventTouchDown];
        delButton.frame = CGRectMake(0, 0, 24, 24);
		delButton.center = CGPointMake(cell.frame.size.width*0.2,cell.frame.size.height*0.2);
        delButton.hidden = YES;
//        delButton.backgroundColor = [UIColor redColor];
        [cell addSubview:delButton];
    }
}

- (void)deletePressed:(UIButton*)sender {
    UIView* view = [sender superview];
    if (view) {
        NSUInteger index = [self.cellArray indexOfObject:view];
        if (index != NSNotFound) {
            [UIView animateWithDuration:0.2
                                  delay:0.0
                                options:0
                             animations:^{
                                 for (NSUInteger i=self.cellArray.count-1; i>index; i--) {
                                     UIView* preView = [self.cellArray objectAtIndex:i-1];
                                     UIView* curView = [self.cellArray objectAtIndex:i];
                                     
                                     curView.center = preView.center;
                                 }
                                 
                                 UIView* delView = [self.cellArray objectAtIndex:index];
                                 [self.cellArray removeObject:delView];
                                 [delView removeFromSuperview];
                             }
                             completion:^(BOOL finished) {
                                 
                                 if (self.delegate) {
                                     [self.delegate deletableCell:self didDeleteItemAtIndex:index];
                                 }
                             }];
        }
    }
}

- (void)longPressed:(UILongPressGestureRecognizer*)gr {
    if (self.isDeleting) {
        return;
    }
    
    self.isDeleting = YES;
    [self startDelete];
}

- (void)tapPressed:(UITapGestureRecognizer*)gr {
	if (self.isDeleting) {
		return;
	}
	
	if (self.delegate) {
        NSUInteger index = [self.cellArray indexOfObject:gr.view.superview];
        if (index != NSNotFound) {
			[self.delegate deletableCell:self didSelectItemAtIndex:index];
		}
	}
}

- (void)startDelete {
    srand([[NSDate date] timeIntervalSince1970]);
    NSUInteger index = 0;
    for (UIView* view in self.cellArray) {
        UIView* delBtn = [view viewWithTag:0xDB];
        if (delBtn && self.delegate && [self.delegate deletableCell:self shouldDeleteItemAtIndex:index++]) {
            delBtn.hidden = NO;
        }
        
        float rand=(float)random();
        CFTimeInterval t=rand*0.0000000001;
        [UIView animateWithDuration:0.1
							  delay:t
							options:0
						 animations:^{
							 view.transform=CGAffineTransformMakeRotation(-0.05);
						 }
						 completion:^(BOOL finished){
							 [UIView animateWithDuration:0.1
												   delay:0
												 options:UIViewAnimationOptionRepeat|UIViewAnimationOptionAutoreverse|UIViewAnimationOptionAllowUserInteraction
											  animations:^{
													 view.transform=CGAffineTransformMakeRotation(0.05);
												 }
											  completion:nil];
						 }];
	}
	
	if (self.delegate && [self.delegate respondsToSelector:@selector(deletableCell:deleteBeginOrEnd:)]) {
		[self.delegate deletableCell:self deleteBeginOrEnd:YES];
	}
}

- (void)stopDelete {
    for (UIView* view in self.cellArray) {
        [view.layer removeAllAnimations];
		view.transform = CGAffineTransformIdentity;
        
        UIView* delBtn = [view viewWithTag:0xDB];
        if (delBtn) {
            delBtn.hidden = YES;
        }
    }
    self.isDeleting = NO;
	
	if (self.delegate && [self.delegate respondsToSelector:@selector(deletableCell:deleteBeginOrEnd:)]) {
		[self.delegate deletableCell:self deleteBeginOrEnd:NO];
	}
}

- (void)reloadData {
    [self recalcLayout];
    [self arrangeCells];
}

- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
